package bb.lanxing.fragment;

import android.content.Context;
import android.content.Intent;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.gyf.immersionbar.ImmersionBar;
import com.squareup.otto.Subscribe;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.activity.login.AccountLoginActivity;
import bb.lanxing.activity.mine.NewMoreActivity;
import bb.lanxing.activity.mine.RankingsOverviewActivity;
import bb.lanxing.activity.mine.UserInfoActivity;
import bb.lanxing.activity.sport.HistoryListActivity;
import bb.lanxing.activity.sport.SportRecordActivity;
import bb.lanxing.adapter.mine.MineInfoPagerAdapter;
import bb.lanxing.adapter.mine.MineListAdapter;
import bb.lanxing.common.config.Constants;
import bb.lanxing.common.config.UmengEventConst;
import bb.lanxing.devicelist.XZDeviceListActivity;
import bb.lanxing.fragment.base.BaseTabFragment;
import bb.lanxing.lib.widget.indicator.PagerIndicator;
import bb.lanxing.manager.SharedManager;
import bb.lanxing.model.bean.LoginModel;
import bb.lanxing.model.database.User;
import bb.lanxing.network.BiCiCallback;
import bb.lanxing.network.DownLoadObserver;
import bb.lanxing.network.DownloadInfo;
import bb.lanxing.network.DownloadManager;
import bb.lanxing.network.MyHttpClient;
import bb.lanxing.util.BusProvider;
import bb.lanxing.util.Log;
import bb.lanxing.utils.IntentUtils;
import bb.lanxing.view.UserAvatarView;
import okhttp3.Request;

public class MineFragment extends BaseTabFragment {
	private UserAvatarView userAvatarView;
	private View notLoginLayout;
	private TextView nameView;

	private PagerIndicator indicator;
	private MineInfoPagerAdapter mineInfoPagerAdapter;

	public MineFragment() {
		super(R.layout.fragment_mine);
	}

	@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_mine, container, false);
	}

	public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		view.findViewById(R.id.app_settings).setOnClickListener(v -> startActivity(new Intent(getContext(), NewMoreActivity.class)));

		userAvatarView = view.findViewById(R.id.userAvatar);
		userAvatarView.setOnClickListener(this::onAvatarClick);
		notLoginLayout = view.findViewById(R.id.notLoginLayout);
		notLoginLayout.setOnClickListener(v -> AccountLoginActivity.launchLoginActivity(requireContext(), 0));
		nameView = view.findViewById(R.id.nameView);

		View bluetoothDevice = view.findViewById(R.id.bluetoothDevice);
		bluetoothDevice.setOnClickListener(this::onSmartDeviceItemClick);

		ViewPager pager = view.findViewById(R.id.pager);
		mineInfoPagerAdapter = new MineInfoPagerAdapter();
		mineInfoPagerAdapter.registerDataSetObserver(new DataSetObserver() {
			@Override public void onChanged() {
				super.onChanged();
				if (indicator != null) {
					if (mineInfoPagerAdapter == null || mineInfoPagerAdapter.getCount() != 1) {
						indicator.setVisibility(View.GONE);
					} else {
						indicator.setVisibility(View.VISIBLE);
					}
				}
			}
		});
		pager.setAdapter(mineInfoPagerAdapter);
		indicator = view.findViewById(R.id.indicator);
		indicator.setViewPager(pager);

		RecyclerView mineList = view.findViewById(R.id.mineList);
		mineList.setLayoutManager(new GridLayoutManager(getContext(), 2));
		mineList.setAdapter(getMineListAdapter());
	}

	private MineListAdapter getMineListAdapter() {
		MineListAdapter mineListAdapter = new MineListAdapter();
		mineListAdapter.setOnItemClickListener(position -> {
			switch (position) {
				case 0:
					onHistoryItemClick();
					break;
				case 1:
					onCareerRecordClick();
					break;
				case 2:
					onMedalItemClick();
					break;
				case 3:
					onClickSportsCareer();
					break;
				case 4:
					onClickMyOrder();
					break;
			}
		});
		return mineListAdapter;
	}

	private void onAvatarClick(View view) {
		if (App.getContext().isUserSignin()) {
			startActivity(new Intent(getContext(), UserInfoActivity.class));
			MobclickAgent.onEventValue(getContext(), UmengEventConst.LEVEL_PERMISSION_INFO, null, 1);
		} else {
			AccountLoginActivity.launchLoginActivity(requireContext(), 0);
		}
	}

	private void onSmartDeviceItemClick(View view) {
		SharedManager.getInstance().setValue(SharedManager.KEY_SHOW_SPRINT_PROMPT_FIRST, false);
		if (App.getContext().isUserSignin()) {
			startActivity(new Intent(getContext(), XZDeviceListActivity.class));
		} else {
			App.getContext().userSignin();
		}
	}

	private void onHistoryItemClick() {
		MobclickAgent.onEventValue(App.getContext(), UmengEventConst.MINE_HISTORY, null, 1);
		if (App.getContext().isUserSignin()) {
			startActivity(new Intent(getContext(), SportRecordActivity.class));
		} else {
			App.getContext().userSignin();
		}
	}

	private void onCareerRecordClick() {
		if (App.getContext().isUserSignin()) {
			long userId = App.getContext().getSigninUser().getUid();
			String url = Constants.URL_CAREER_RECORD + "?id=" + userId;
			IntentUtils.gotoWebBrowser(getContext(), url, getResources().getString(R.string.mine_career_record), true);
		} else {
			App.getContext().userSignin();
		}
	}

	private void onMedalItemClick() {
		if (App.getContext().isUserSignin()) {
			startActivity(new Intent(getContext(), RankingsOverviewActivity.class));
		} else {
			App.getContext().userSignin();
		}
	}

	private void onClickSportsCareer() {
		if (App.getContext().isUserSignin()) {
			User signinUser = App.getContext().getSigninUser();
			Context requireContext = requireContext();

			String MINE_SPORTS_CAREER = Constants.MINE_SPORTS_CAREER_A;

			String url = MINE_SPORTS_CAREER + "?id=" + signinUser.getUid();
			IntentUtils.gotoWebBrowser(requireContext, url, getString(R.string.mine_sports_career));
		} else {
			App.getContext().userSignin();
		}
	}

	private void onClickMyOrder() {
		String url1 = "https://woc.bluebank.com.cn/prod-api/fota/download/compress16-17bike.bin";
		DownloadManager.getInstance().download(url1, new DownLoadObserver() {
			@Override public void onNext(DownloadInfo value) {
				super.onNext(value);
				Log.d("DownloadObserver", "onNext: setMax:" + (int) value.getTotal());
				Log.d("DownloadObserver", "onNext: setProgress:" + (int) value.getProgress());
			}

			@Override public void onError(Exception e) {
				Log.d("wrong:");
			}

			@Override public void onComplete() {
				if (downloadInfo != null) {
					Toast.makeText(App.getContext(), downloadInfo.getFileName() + "-DownloadComplete", Toast.LENGTH_SHORT).show();
				}
			}
		});
	}

	@Override public void onResume() {
		super.onResume();
		ImmersionBar.with(this).transparentStatusBar().statusBarDarkFont(false).init();
		loadData();
	}

	public void loadData() {
		if (SharedManager.getInstance().isUseAgreementAgree()) {
			if (App.getContext().isUserSignin()) {
				BiCiCallback biCiCallback = new BiCiCallback() {
					@Override public void onFailure(Request request, IOException e) {
						super.onFailure(request, e);
					}

					@Override public void onResponseString(@NonNull String string) {
						if (!TextUtils.isEmpty(string)) {
							try {
								User user = App.getContext().getSigninUser();
								user.update(new JSONObject(string));
								user.save();
								SharedManager.getInstance().setUserId(user.getUid());
								SharedManager.getInstance().setUsername(user.getName());
								SharedManager.getInstance().setPassword("");
								SharedManager.getInstance().setUserPhone(user.getPhone());
								SharedManager.getInstance().setEmail(user.getEmail());
								runOnUIThread(() -> updateUserInfo(user));
							} catch (JSONException e) {
								throw new RuntimeException(e);
							}
						}
					}
				};
				MyHttpClient.requestUserInfo(biCiCallback, App.getContext().getSigninUser().getUid());
			} else {
				userAvatarView.resetAvatar();
				notLoginLayout.setVisibility(View.VISIBLE);
				nameView.setVisibility(View.GONE);
			}
		}
	}

	private void updateUserInfo(User user) {
		if (user != null && userAvatarView != null) {
			Log.i("updateUserInfo user level = " + user.getLevel());
			userAvatarView.setAvatarMode(UserAvatarView.AVATAR_SIZE_60);
			userAvatarView.enableAvatarBorder();
			userAvatarView.setAvatarForUrl(user.getPhotoUrl());
			userAvatarView.setUserLevelText(user.getLevel());
			nameView.setText(user.getName());
			nameView.setVisibility(View.VISIBLE);
			notLoginLayout.setVisibility(View.GONE);
		}
		if (mineInfoPagerAdapter != null) {
			mineInfoPagerAdapter.setUser(user);
		}
	}

	@Override public void onDestroy() {
		BusProvider.getInstance().unregister(this);
		super.onDestroy();
	}

	@Override public void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		BusProvider.getInstance().register(this);
	}

	@Subscribe public void updateUser(LoginModel loginModel) {
		Log.i("updateUser id = " + loginModel);
		if (!loginModel.isQuit()) {
			updateUserInfo(App.getContext().getSigninUser());
		} else {
			userAvatarView.resetAvatar();
			notLoginLayout.setVisibility(View.VISIBLE);
			nameView.setVisibility(View.GONE);
		}
	}
}
